const FfmpegCommand = require('fluent-ffmpeg');
const http = require('http');
const ffmpegPath = require('@ffmpeg-installer/ffmpeg').path.replace(
  'app.asar',
  'app.asar.unpacked'
);
const ffprobePath = require('@ffprobe-installer/ffprobe');
FfmpegCommand.setFfmpegPath(ffmpegPath);
FfmpegCommand.setFfprobePath(ffprobePath);
// FfmpegCommand.getAvailableFormats(function (err, formats) {
//   console.log('Available formats:');
//   console.dir(formats);
// });

// FfmpegCommand.getAvailableCodecs(function (err, codecs) {
//   console.log('Available codecs:');
//   console.dir(codecs);
// });
class VideoServer {
  port: number;
  videoPath: any;
  server: any;
  constructor(videoPath) {
    this.port = 8888;
    this.videoPath = videoPath;
    this.videoSupport(videoPath);
  }

  videoSupport = (videoPath) => {
    const supportFormats = ['mp4', 'webm'];
    const format = videoPath.substring(videoPath.lastIndexOf('.') + 1);
    return supportFormats.includes(format);
  };

  start() {
    this.server = http
      .createServer((request, response) => {
        try {
          console.log(request.url, '收到请求');
          if (this.videoSupport(this.videoPath)) {
            response.writeHead(307, {
              Location: `file://${this.videoPath}`
            });
            response.end();
          } else {
            const ffmpeg = new FfmpegCommand();
            const startTime = parseInt(getParam(request.url, 'startTime'));
            const outStream = ffmpeg
              .input(this.videoPath)
              .nativeFramerate()
              .videoCodec('libx264')
              .audioCodec('aac')
              .format('mp4')
              .seekInput(startTime)
              .outputOptions('-movflags', 'frag_keyframe+empty_moov+faststart', '-g', '18')
              .on('progress', function (progress) {
                console.log(`time: ${progress.timemark}`);
              })
              .on('error', function (err) {
                console.log(`An error occurred: ${err.message}`);
              })
              .on('end', function () {
                console.log('Processing finished !');
              });
            outStream.pipe(response);
          }
        } catch (error) {
          console.log(error);
        }
      })
      .listen(this.port, () => {
        console.log(`启动${this.port}`);
      });
  }
}

exports.formatVideo = function (
  { source, format = 'flv', encoder, cacheDir = '' },
  callback: (status: string) => void
) {
  const command = new FfmpegCommand();
  const prefix = source.substring(0, source.lastIndexOf('.'));
  console.log('格式话文件名前缀', prefix, cacheDir);
  const outputPath = `${prefix}.${format.toLowerCase()}`;
  command
    .input(source)
    .format(format.toLowerCase())
    .videoCodec(encoder)
    .on('error', (err) => {
      console.log('转码失败', err);
      callback('error');
    })
    .save(outputPath)
    .on('end', () => {
      callback('success');
      console.log('转码成功');
    });
};

function getParam(url, key) {
  const param = {};
  let item = [];
  const urlList = url.split('?');
  let req;
  if (urlList.length === 1) {
    req = urlList[0];
  } else {
    req = urlList[1];
  }
  const list = req.split('&');
  for (let i = 0; i < list.length; i++) {
    item = list[i].split('=');
    param[item[0]] = item[1];
  }
  return param[key] ? param[key] : null;
}

export { VideoServer };
